import 'package:flutter/material.dart';
import 'package:my_shop/timer/timer_task_id.dart';
import 'dart:convert';

/// 定时任务配置
class TimerTaskConfig {
  /// 任务ID
  final TimerTaskId taskId;
  
  /// 执行间隔时间（与specificTime二选一）
  final Duration? interval;
  
  /// 每日固定执行时间点（与interval二选一）
  final TimeOfDay? specificTime;
  
  /// 任务回调函数
  final VoidCallback callback;

  /// 是否在注册时立即执行一次
  final bool? executeImmediately;

  /// 是否在服务初始化时执行过期任务
  final bool? executeOnInitIfExpired;

  TimerTaskConfig({
    required this.taskId,
    required this.callback,
    this.interval,
    this.specificTime,
    this.executeImmediately = false,
    this.executeOnInitIfExpired = false,
  }) : assert(
    (interval != null && specificTime == null) || 
    (interval == null && specificTime != null),
    '必须且只能设置interval或specificTime之一'
  );

  /// 从JSON创建配置
  factory TimerTaskConfig.fromJson(String jsonStr) {
    final json = jsonDecode(jsonStr);
    return TimerTaskConfig(
      taskId: TimerTaskId.values.firstWhere(
        (id) => id.id == json['taskId'],
      ),
      interval: json['interval'] != null ? Duration(seconds: json['interval']) : null,
      specificTime: json['specificTime'] != null 
        ? TimeOfDay(
            hour: json['specificTime']['hour'],
            minute: json['specificTime']['minute'],
          )
        : null,
      callback: () {}, // 回调函数无法序列化，需要在恢复时重新设置
      executeImmediately: json['executeImmediately'] ?? false,
      executeOnInitIfExpired: json['executeOnInitIfExpired'] ?? false,
    );
  }

  /// 转换为JSON
  String toJson() {
    return jsonEncode({
      'taskId': taskId.id,
      'interval': interval?.inSeconds,
      'specificTime': specificTime != null 
        ? {
            'hour': specificTime!.hour,
            'minute': specificTime!.minute,
          }
        : null,
      'executeImmediately': executeImmediately,
      'executeOnInitIfExpired': executeOnInitIfExpired,
    });
  }
}
